package crm8000.services

import groovy.sql.Sql

import javax.sql.DataSource

import crm8000.Models.Org
import crm8000.Models.Permission
import crm8000.Models.Role;
import crm8000.Models.User
import crm8000.helper.Result

class PermissionService {
	def UserService userService

	Boolean hasPermission(String fid) {
		if (!fid) return true

		if (["-9999", "-9997", "-9996"].contains(fid)) return true

		def c = Role.createCriteria()
		def roleCount = c.count {
			users {
				eq("id", userService.loginUserId)
			}
			permission {
				eq("fid", fid)
			}
		}

		return roleCount > 0
	}

	def roleList() {
		return Role.listOrderByName()
	}

	def permissionList(String roleId) {
		def role = Role.get(roleId)
		if (role == null) {
			return []
		}

		return role.permission.toList()
	}

	def userList(String roleId) {
		def role = Role.get(roleId)
		if (role == null) {
			return []
		}

		return role.users.toList()
	}

	Result editRole(params) {
		def permissionIdList = params.permissionIdList == null ? []: params.permissionIdList.split(",")
		def userIdList = params.userIdList == null ? []: params.userIdList.split(",")

		if (params.id) {
			// 编辑
			def role = Role.get(params.id)
			if (!role) {
				return new Result(success: false, msg: "角色不存在");
			}

			role.permission.clear()
			role.users.clear()
			for (id in permissionIdList) {
				def p = Permission.get(id)
				if (p) {
					role.addToPermission(p)
				}
			}

			for (id in userIdList){
				def u = User.get(id)
				if (u) {
					role.addToUsers(u)
				}
			}

			role.save()
			return new Result(success: true, id: role.id)
		} else {
			// 新建
			def role = new Role(name: params.name)
			for (id in permissionIdList) {
				def p = Permission.get(id)
				if (p) {
					role.addToPermission(p)
				}
			}

			for (id in userIdList){
				def u = User.get(id)
				if (u) {
					role.addToUsers(u)
				}
			}

			role.save()

			return new Result(success: true, id: role.id)
		}
	}

	def selectPermission(params) {
		def result = []
		def idList = params.idList == null ? []: params.idList.split(",")
		for (p in Permission.list(sort: "name")) {
			if (!idList.contains(p.id)) {
				result.add(p)
			}
		}

		return result
	}

	def selectUsers(params) {
		def result = []
		def idList = params.idList == null ? []: params.idList.split(",")
		for (u in User.list(sort: "loginName")) {
			if (!idList.contains(u.id)) {
				result.add(u)
			}
		}
		return result
	}

	Result deleteRole(String roleId) {
		def role = Role.get(roleId)
		if (!role) {
			return new Result(success: false, msg: "角色不存在")
		}

		role.delete()

		return new Result(success: true)
	}
}